<template>
  <div class="admin-account-list">
    <!-- 搜索和操作区域 -->
    <div class="operation-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="账号">
          <el-input v-model="searchForm.username" placeholder="请输入账号" clearable />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="searchForm.nickName" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="operation-buttons">
        <el-button type="primary" @click="handleAdd">添加管理员</el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="adminList"
      border
      style="width: 100%"
    >
      <el-table-column type="index" width="50" />
      <el-table-column prop="username" label="账号" width="150" />
      <el-table-column prop="phone" label="手机号" width="120" />
      <el-table-column prop="email" label="邮箱" min-width="180" />
      <el-table-column prop="roleId" label="角色" width="120">
        <template #default="{ row }">
          <el-tag :type="getRoleType(row.roleId)">
            {{ getRoleName(row.roleId) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusName(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="loginFailCount" label="登录失败次数" width="100">
        <template #default="{ row }">
          <el-tag :type="row.loginFailCount > 5 ? 'danger' : 'info'">
            {{ row.loginFailCount }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="lastLoginIp" label="最后登录IP" width="120" />
      <el-table-column prop="lastLoginTime" label="最后登录时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.lastLoginTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="twoFaEnabled" label="双因素认证" width="100">
        <template #default="{ row }">
          <el-tag :type="row.twoFaEnabled ? 'success' : 'info'">
            {{ row.twoFaEnabled ? '已启用' : '未启用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button 
            type="primary" 
            link 
            @click="handleStatusChange(row)"
            :disabled="row.roleId === 1"
          >
            {{ getStatusActionName(row.status) }}
          </el-button>
          <el-button 
            type="primary" 
            link 
            @click="handleResetPassword(row)"
          >
            重置密码
          </el-button>
          <el-button 
            type="primary" 
            link 
            @click="handleTwoFa(row)"
          >
            {{ row.twoFaEnabled ? '关闭2FA' : '开启2FA' }}
          </el-button>
          <el-button 
            type="danger" 
            link 
            @click="handleDelete(row)"
            :disabled="row.roleId === 1"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑管理员' : '添加管理员'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="账号" prop="username">
          <el-input 
            v-model="formData.username" 
            placeholder="请输入账号"
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="formData.roleId" placeholder="请选择角色">
            <el-option
              v-for="(role, id) in roleMap"
              :key="id"
              :label="role.name"
              :value="Number(id)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
            <el-radio :value="2">锁定</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="双因素认证" prop="twoFaEnabled">
          <el-switch v-model="formData.twoFaEnabled" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input 
            v-model="formData.password" 
            type="password" 
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 2FA设置对话框 -->
    <el-dialog
      v-model="twoFaDialogVisible"
      title="设置双因素认证"
      width="400px"
    >
      <div v-if="!twoFaData.secret">
        <p>请使用Google Authenticator扫描下方二维码：</p>
        <div class="qrcode-container">
          <img :src="twoFaData.qrCode" alt="2FA QR Code" />
        </div>
        <p>或手动输入密钥：{{ twoFaData.secret }}</p>
        <el-form
          ref="twoFaFormRef"
          :model="twoFaForm"
          :rules="twoFaRules"
          label-width="100px"
        >
          <el-form-item label="验证码" prop="code">
            <el-input v-model="twoFaForm.code" placeholder="请输入6位验证码" />
          </el-form-item>
        </el-form>
      </div>
      <div v-else>
        <p>确定要关闭双因素认证吗？</p>
        <el-form
          ref="twoFaFormRef"
          :model="twoFaForm"
          :rules="twoFaRules"
          label-width="100px"
        >
          <el-form-item label="验证码" prop="code">
            <el-input v-model="twoFaForm.code" placeholder="请输入6位验证码" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="twoFaDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleTwoFaSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAdminList, addAdmin } from '@/api/admin'

const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const adminList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const formRef = ref(null)

// 搜索表单
const searchForm = ref({
  username: '',
  nickName: '',
  status: ''
})

// 角色映射
const roleMap = {
  1: { name: '超级管理员', type: 'danger' },
  2: { name: '商品管理员', type: 'warning' },
  3: { name: '订单管理员', type: 'primary' },
  4: { name: '用户管理员', type: 'success' }
}

// 获取角色名称
const getRoleName = (roleId) => {
  return roleMap[roleId]?.name || '未知角色'
}

// 获取角色标签类型
const getRoleType = (roleId) => {
  return roleMap[roleId]?.type || 'info'
}

// 状态映射
const statusMap = {
  0: { name: '禁用', type: 'info', action: '启用' },
  1: { name: '启用', type: 'success', action: '禁用' },
  2: { name: '锁定', type: 'danger', action: '解锁' }
}

// 获取状态名称
const getStatusName = (status) => {
  return statusMap[status]?.name || '未知状态'
}

// 获取状态标签类型
const getStatusType = (status) => {
  return statusMap[status]?.type || 'info'
}

// 获取状态操作名称
const getStatusActionName = (status) => {
  return statusMap[status]?.action || '修改状态'
}

// 获取管理员列表
const fetchAdminList = async () => {
  loading.value = true
  try {
    const res = await getAdminList()
    adminList.value = res || []
    total.value = res.length || 0
  } catch (error) {
    console.error('获取管理员列表失败：', error)
    ElMessage.error('获取管理员列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchAdminList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    username: '',
    nickName: '',
    status: ''
  }
  handleSearch()
}

// 添加管理员
const handleAdd = () => {
  isEdit.value = false
  formData.value = {
    username: '',
    phone: '',
    email: '',
    roleId: 2,
    status: 1,
    password: '',
    twoFaEnabled: false
  }
  dialogVisible.value = true
}

// 编辑管理员
const handleEdit = (row) => {
  isEdit.value = true
  formData.value = { ...row }
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    submitting.value = true
    if (isEdit.value) {
      await service.put(`/admin/accounts/${formData.value.id}`, formData.value)
      ElMessage.success('修改成功')
    } else {
      await addAdmin(formData.value)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    fetchAdminList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交失败：', error)
      ElMessage.error('提交失败，请检查表单')
    }
  } finally {
    submitting.value = false
  }
}

// 修改状态
const handleStatusChange = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 1 ? '禁用' : '启用'}该管理员吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await service.put(`/admin/accounts/${row.id}/status`, {
      status: row.status === 1 ? 0 : 1
    })
    
    ElMessage.success('操作成功')
    fetchAdminList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('修改状态失败：', error)
      ElMessage.error('操作失败')
    }
  }
}

// 重置密码
const handleResetPassword = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要重置该管理员的密码吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await service.put(`/admin/accounts/${row.id}/password/reset`)
    
    ElMessage.success('密码重置成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置密码失败：', error)
      ElMessage.error('重置失败')
    }
  }
}

// 删除管理员
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该管理员吗？此操作不可恢复！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await service.delete(`/admin/accounts/${row.id}`)
    
    ElMessage.success('删除成功')
    fetchAdminList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除管理员失败：', error)
      ElMessage.error('删除失败')
    }
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchAdminList()
}

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchAdminList()
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 2FA相关
const twoFaDialogVisible = ref(false)
const twoFaData = ref({
  secret: '',
  qrCode: ''
})
const twoFaForm = ref({
  code: ''
})
const twoFaRules = {
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '请输入6位数字验证码', trigger: 'blur' }
  ]
}

// 处理2FA设置
const handleTwoFa = async (row) => {
  try {
    if (!row.twoFaEnabled) {
      // 开启2FA
      const res = await service.post(`/admin/accounts/${row.id}/2fa/enable`)
      twoFaData.value = res.data
    } else {
      // 关闭2FA
      twoFaData.value = { secret: row.twoFaSecret }
    }
    twoFaDialogVisible.value = true
  } catch (error) {
    console.error('获取2FA信息失败：', error)
    ElMessage.error('操作失败')
  }
}

// 提交2FA设置
const handleTwoFaSubmit = async () => {
  if (!twoFaFormRef.value) return
  
  try {
    await twoFaFormRef.value.validate()
    submitting.value = true

    const action = twoFaData.value.secret ? 'disable' : 'enable'
    await service.post(`/admin/accounts/${currentAdmin.value.id}/2fa/${action}`, {
      code: twoFaForm.value.code
    })

    ElMessage.success('设置成功')
    twoFaDialogVisible.value = false
    getAdminList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('设置失败：', error)
      ElMessage.error('设置失败，请检查验证码')
    }
  } finally {
    submitting.value = false
  }
}

// 表单数据
const formData = ref({
  username: '',
  phone: '',
  email: '',
  roleId: 2,
  status: 1,
  password: '',
  twoFaEnabled: false
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

onMounted(() => {
  fetchAdminList()
})
</script>

<style lang="scss" scoped>
.admin-account-list {
  .operation-area {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .search-form {
      flex: 1;
    }

    .operation-buttons {
      margin-left: 20px;
    }
  }

  .pagination-area {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .qrcode-container {
    text-align: center;
    margin: 20px 0;
    
    img {
      max-width: 200px;
      max-height: 200px;
    }
  }
}
</style>
